// 获取应用实例
const app = getApp()
const api = app.globalData.api

Page({
    data: {
        info: [],
        reportWork: [],
        calendarType: 'date',
        nowDate: new Date().getTime(),
        teamStaffDisplay:'hidden',
        detail: {},
        total: 0,
        count: 0,
        dateField: '',
        prefix: '',
        teamTypeOption: [],
        problemOption: [],
        processNameOption: [],
        teamOption: {},
        teamStaffOption: {}
    },

    main: async function () {
        await this.getTeamType()
        await this.getTeam()
    },
    getTeamType: async function () {
        let res = await api.curlGet('?cla=processReport&fun=getTeamType')
        if (res.code === 1) {
            this.setData({
                teamTypeOption: res.data
            })
        }
    },
    getTeamStaff: async function (teamId) {
        let res = await api.curlPost('?cla=processReport&fun=getTeamStaff', {'teamId': teamId})
        if (res.code === 1) {
            this.setData({
                teamStaffOption: res.data
            })
        }
    },
    getTeam: async function () {
        let res = await api.curlGet('?cla=processReport&fun=getTeam')
        if (res.code === 1) {
            this.setData({
                teamOption: res.data
            })
        }
    },
    getProcessNameOption: async function () {
        this.setData({
            processNameOption: wx.getStorageSync('processNameOption')
        })
        wx.removeStorageSync('processNameOption')
    },
    // 更新本地数据
    getDetail: async function (id) {
        let res = await api.curlPost('?cla=processReport&fun=detail', {id: id})
        if (res.code === 1) {
            const resp = res.data.result
            this.setData({
                info: resp.info,
                reportWork: resp.reportWork,
                detail: resp.detail,
                problemOption: resp.problem
            })
            const objString = JSON.stringify(resp.detail)
            let problemData = (objString === '[]') ? {} : resp.detail
            wx.setStorageSync('problemData', problemData)
        }
    },
    assign: async function (data) {
        const obj = api.jsonToArray(data)
        this.setData({
            info: obj,
            problemOption: obj.problem
        })
    },
    // 扫码
    onScan: async function (e) {
        const that = this
        wx.scanCode({
            onlyFromCamera: true,
            async success(res) {
                if (res.errMsg === "scanCode:ok") {
                    const string = res.result
                    let array = api.parseStr(string)
                    if (['machining_send_order', 'machining_card'].includes(array['source'])) {
                        let res = await api.curlPost('?cla=processReport&fun=getMaterial', {
                            source: array['source'],
                            id: array['id']
                        })
                        if (res.code === 1) {
                            if (res.data.page.sqlNum <= 0) {
                                api.showToast('暂无该单据数据')
                            } else {
                                let processOption = []
                                for (const result of res.data.result) {
                                    processOption.push({
                                        'text': result['processName'],
                                        'value': api.arrayToJson(result)
                                    })
                                }
                                console.log(processOption)
                                wx.setStorageSync('processNameOption', processOption)
                                wx.navigateTo({
                                    url: 'add?data=' + api.arrayToJson(res.data.result[0]),
                                })
                            }
                        }
                    }
                }
            }
        })
    },
    onShow: async function () {
        const problem = wx.getStorageSync('problemData')
        if (problem) {
            this.setData({
                detail: problem
            })
        }
    },
    // 渲染
    onLoad: async function (options) {
        let that = this,
            id = options.id ? options.id : '',
            data = options.data ? options.data : ''
        if (id) {
            await that.getDetail(id)
        }
        if (data) {
            await that.assign(data)
            await this.getProcessNameOption()
        }
        await that.main()
    },
    onDisplay: function (e) {
        let obj = e.currentTarget.dataset
        let prefix = obj.prefix ? obj.prefix : 'info'
        let formate = obj.calendar ? obj.calendar : 'date'
        this.setData({
            calendar: true,
            prefix: prefix,
            calendarType: formate,
            dateField: obj.field
        })
    },
    // 关闭
    onClose: function (e) {
        let obj = e.currentTarget.dataset
        if (obj) {
            this.setData({[obj.target]: false})
        }
    },

    goto(e) {
        return api.goto(e)
    },
    funRouting: function (type, detail, prefix, formate) {
        const array = detail.value
        switch (type) {
            // 选项与值相等
            case 'workshop':
                this.setData({
                    lineOption: this.getLine('lineOption', array['text'])
                })
                return array['text']
            // 选项与值为key value
            case 'teamName':
                this.setData({
                    [prefix + '.teamId']: array['value']
                })
                if(this.data.info.valuationType === '个人计件'){
                    this.getTeamStaff(array['value'])
                    this.setData({
                        'teamStaffDisplay': ''
                    })
                }
                return array['text']
            case 'teamStaff':
                this.setData({
                    [prefix + '.teamStaffId']: array['value']
                })
                return array['text']
            // 日期
            case 'teamNo':
            case 'startTime':
            case 'endTime':
            case 'startDate':
            case 'endDate':
                return api.formatDate(detail, formate)
            case 'processName':
                if (detail.value.value.length === 0) {
                    return
                }
                wx.navigateTo({
                    url: 'add?data=' + detail.value.value,
                })
                return detail.value.value['processName']
            // 单字符串
            default:
                return detail.value
        }
    },
    // 确认选择
    onConfirm: function (e) {
        let obj = e.currentTarget.dataset
        let prefix = obj.prefix ? obj.prefix : 'info'
        let formate = obj.formate ? obj.formate : 'date'
        let field = (prefix ? prefix + '.' : '') + obj.field
        this.setData({
            [obj.target]: false,
            [field]: this.funRouting(obj.field, e.detail, prefix, formate),
        })
    },
    showPopup: function (obj) {
        let popup = obj.currentTarget.dataset.show
        if (popup === 'processNamePopup' && this.data.processNameOption.length === 0) {
            return false
        }
        if (popup) {
            this.setData({
                [popup]: true
            });
        }
    },
    delRow: function (obj) {
        const id = obj.currentTarget.dataset.id
        let array = this.data.detail
        delete array[id]
        this.setData({
            detail: array
        })
        wx.setStorageSync('problemData', array)
    },
    formSubmit: async function (e) {
        const problem = wx.getStorageSync('problemData')
        let obj = e.detail.value
        if (obj) {
            obj['detail'] = api.arrayToJson(problem)
            let res = await api.curlPost('?cla=processReport&fun=edit', obj)
            if (res.code === 1) {
                wx.navigateTo({
                    url: 'detail?id=' + res.data
                })
                wx.removeStorageSync('problemData')
                api.showToast('新增成功', 'success')
            } else {
                api.showToast(res.warn)
            }
        }
    },
    previewFile: async function (obj) {
      let data = obj.currentTarget.dataset
      if (!data.src) {
          return api.showToast('参数错误')
      }
      const fileLink = data.src
      api.showLoading()
      // 单次下载允许的最大文件为 200MB
      wx.downloadFile({
          url: fileLink,
          success: function (res) {
              console.log(res, "wx.downloadFile success res")
              if (res.statusCode !== 200) {
                  util.hideLoadingWithErrorTips()
                  return false
              }
              var Path = res.tempFilePath //返回的文件临时地址，用于后面打开本地预览所用
              wx.openDocument({
                  filePath: Path,
                  showMenu: true,
                  success: function (res) {
                      console.log('打开成功');
                      api.hideLoading()
                  }
              })
          },
          fail: function (err) {
              console.log(err, "wx.downloadFile fail err");
          }
      })

  }
});
